const app = document.querySelector('#app');

console.log(app)

class Router{
    constructor({mode='hash',routes=[]}){
        this.mode = mode;
        this.routes = routes;
        //初始化视图
        this.init();
    }

    init(){
        let pathname = location.pathname; //  /
        if(this.mode === 'hash'){
            location.href = location.origin + '/#' + pathname;
        }
        //根据地址渲染视图
        this.render(pathname);
    }

    //渲染视图
    render(pathname){
        let targetView = routes.find(item => item.path === pathname);
        if(targetView){
            app.innerHTML = targetView.component;
        }
        //点击a标签跳转对应的路由
        this.preventA();
    }

    preventA(){
        let allA = [...document.querySelectorAll('a')];

        allA.forEach(a => {
            a.onclick = (e)=>{
                //阻止默认行为
                e.preventDefault();
                this.push(e.target.getAttribute('href'));
            }
        })
    }

    //跳路由

    push(url){
        //hash history  h5 api history
        if(this.mode === 'hash'){
            location.href = location.origin + '/#' + url;
        }else{
            //history
            window.history.push({},'',url)
        }
        //渲染对应的视图
        this.render(url);
    }


}